package com.jlu.es;

import com.jlu.es.dao.ProductDao;
import com.jlu.es.domain.Product;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataEsTest {


  @Autowired
  private ElasticsearchRestTemplate elasticsearchRestTemplate;

  @Autowired
  private ProductDao productDao;

  @Test
  public void createIndex() {

//    自动读取配置文件并创建索引
    System.out.println("创建索引");
  }


  //  新增数据
  @Test
  public void createData() {

    Product product = new Product();
    product.setId(2l);
    product.setCategory("手机");
    product.setTitle("华为手机");
    product.setPrice(3999.0);
    product.setImages("https://p1.ssl.qhimg.com/t0127221d43c01499c4.png");
    productDao.save(product);
  }

  //  更新数据
  @Test
  public void updateData() {

    Product product = new Product();
    product.setId(2l);
    product.setCategory("手机");
    product.setTitle("华为手机");
    product.setPrice(9999.0);
    product.setImages("https://p1.ssl.qhimg.com/t0127221d43c01499c4.png");
    productDao.save(product);
  }

  //  删除数据
  @Test
  public void deleteData(){

    Product product = new Product();
    product.setId(2l);
    productDao.delete(product);
  }
//  通过id查询
  @Test
  public void findById(){
    System.out.println(productDao.findById(2l));
  }

//  查询所有
  @Test
  public void findAll(){
    Iterable<Product> products = productDao.findAll();
    for (Product product : products) {
      System.out.println(product);
    }

  }

//  批量新增
  @Test
  public void batchCreate(){

    ArrayList<Product> list = new ArrayList<Product>();

    for (int i = 0; i < 10; i++) {
      Product product = new Product();
      product.setId(Long.valueOf(i));
      product.setCategory("手机");
      product.setTitle("华为手机" + i);
      product.setPrice(9999.0 + i);
      product.setImages("https://p1.ssl.qhimg.com/t0127221d43c01499c4.png");
      list.add(product);
    }
    productDao.saveAll(list);

  }

//  分页查询
  @Test
  public void page(){
//  设置排序(排序方式，正序还是倒序，排序的id)
    Sort sort = Sort.by(Sort.Direction.DESC,"id");
//  当前页，第一页从0开始，1表示第二页
    int from=0;
//  每页显示多少条
    int size = 5;
//  设置查询分页
    PageRequest pageRequest = PageRequest.of(from,size,sort);//分页查询
    Page<Product> productPage = productDao.findAll(pageRequest);for (Product Product : productPage.getContent()) {
      System.out.println(Product);
    }

  }


}
